package thread;

import utils.PrintUtils;

class Program implements Runnable {

    //锁标志获取对象
    public static Object obj1 = new Object();
    public static Object obj2 = new Object();

    public int flag = 1;


    @Override
    public void run() {
        if (flag == 1) {
            synchronized (obj1) {
                PrintUtils.println("flag:" + flag + ",锁住了资源obj1");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                PrintUtils.println("flag:" + flag + ",等待获取资源obj2");
                synchronized (obj2) {
                    PrintUtils.println("flag:" + flag + "获得资源obj2");
                }
            }
        } else if (flag == 2) {
            synchronized (obj2) {
                PrintUtils.println("flag:" + flag + ",锁住了资源obj2");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                PrintUtils.println("flag:" + flag + ",等待获取资源obj1");
                synchronized (obj1) {
                    PrintUtils.println("flag:" + flag + "获得资源obj1");
                }
            }
        }
    }
}

/**
 * 验证死锁,死锁产生的必要条件
 * 1.至少两个线程
 * 2.资源互斥
 */
public class LockWithLock {
    public static void main(String[] args) {
        Program p1 = new Program();
        Program p2 = new Program();
        p1.flag = 1;
        p2.flag = 2;

        new Thread(p1).start();
        new Thread(p2).start();
    }
}
